# -*- coding: utf-8 -*-

"""
@author: 猿小天
@contact: QQ:1638245306
@Created on: 2021/6/3 003 0:30
@Remark: 用户管理
"""

from rest_framework.permissions import IsAuthenticated

from ops.workflow.models import Ticket
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from dvadmin.utils.json_response import SuccessResponse
from django.db.models import Q




class TicketSerializer(CustomModelSerializer):
    """
    工单管理-序列化器
    """

    class Meta:
        model = Ticket
        read_only_fields = ["id"]
        fields = "__all__"

class TicketCreateUpdateSerializer(CustomModelSerializer):
    """
    工单管理-序列化器
    """

    class Meta:
        model = Ticket
        read_only_fields = ["id"]
        fields = "__all__"



class TicketViewSet(CustomModelViewSet):
    """
    工单管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    permission_classes = [IsAuthenticated]
    queryset = Ticket.objects.all()
    serializer_class = TicketSerializer
    search_fields = ['name']
    create_serializer_class = TicketCreateUpdateSerializer
    update_serializer_class = TicketCreateUpdateSerializer

    def list(self, request, *args, **kwargs):

        # 获取当前登录用户id
        current_user_id = request.user.id

        # querytype查询类别 myself-我创建的 related-我相关的 _todo-我的待办
        querytype = request.query_params.get('querytype')
        temp_queryset = self.get_queryset()

        if querytype == "myself":
            temp_queryset = temp_queryset.filter(creator=current_user_id)
        if querytype == "related":
            temp_queryset = temp_queryset.filter(Q(creator=current_user_id) | Q(approver=current_user_id) | Q(executor=current_user_id))
        if querytype == "todo":
            temp_queryset = temp_queryset.filter(Q(approver=current_user_id) | Q(executor=current_user_id))

        queryset = self.filter_queryset(temp_queryset)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True, request=request)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True, request=request)
        return SuccessResponse(data=serializer.data, msg="获取成功")


